import base64
from bs4 import *


def file_to_base64(file_path):
    with open(file_path, 'rb') as f:  # 以二进制读模式打开文件
        file_bytes = f.read()  # 读取文件字节流
        base64_bytes = base64.b64encode(file_bytes)  # 编码
        return base64_bytes.decode('utf-8')  # 转为字符串

fn = input("Jar File Name:")
cfn = input("Genarate File Name:")
tfn = input("Template File Name:")

fnbs64 = file_to_base64(fn)

if tfn == "":
    with open(cfn, "w", encoding="utf-8") as f:
        f.write("""<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script src="https://cjrtnc.leaningtech.com/4.2/loader.js"></script>
    <title>Document</title>
</head>

<body>
    <script>
        """ + f"""function {"base64ToBlob"}(base64Str, mimeType = 'application/octet-stream') {{
  const base64Data = base64Str.replace(/^data:.*;base64,/, '');
  const binaryStr = atob(base64Data);
  const len = binaryStr.length;
  const uint8Array = new Uint8Array(len);
  for (let i = 0; i < len; i++) {{
    uint8Array[i] = binaryStr.charCodeAt(i);
  }}
  return new Blob([uint8Array], {{ type: mimeType }});
}}
function {"gb"}() {{
            const imgBase64 = "{fnbs64}";
// 转换为 Blob（自动识别 MIME 类型，或手动指定）
const imgBlob = base64ToBlob(imgBase64);

// 生成 Blob URL 并在 img 标签中显示
const blobUrl = URL.createObjectURL(imgBlob, "data:application/java-archive");
// 用完后释放 Blob URL（避免内存泄漏）
//   URL.revokeObjectURL(blobUrl);
return blobUrl;
            }}""" + """
        async function downloadFileToCheerpJ() {
            const response = await fetch(gb());
            const reader = response.body.getReader();
            const contentLength = +response.headers.get('Content-Length');

            const bytes = new Uint8Array(contentLength);

            let pos = 0;
            while (true) {
                const { done, value } = await reader.read();
                if (done)
                    break;
                bytes.set(value, pos);
                pos += value.length;
            }

            // Write to CheerpJ filesystem
            return new Promise((resolve, reject) => {
                var fds = [];
                cheerpOSOpen(fds, "/files/"""+ fn +""".jar", "w", fd => {
                    cheerpOSWrite(fds, fd, bytes, 0, bytes.length, w => {
                        cheerpOSClose(fds, fd, resolve);
                    });
                });
            });
        }

        ((async () => {
            await cheerpjInit({
                version: 17
            });
            cheerpjCreateDisplay(600, 900)
            await downloadFileToCheerpJ()
            cheerpjRunJar("/files/"""+ fn +""".jar")
        })())""" + """
    </script>
</body>

</html>""")

else:
    with open(tfn, "r", encoding="utf-8") as f:
        dc = f.read()

    soup = BeautifulSoup(dc, "html5lib")

    cea = soup.find(id="cheerpj_embedded_area")

    if cea != None:
        s = soup.new_tag("script")
        s.string = f"""function {"base64ToBlob"}(base64Str, mimeType = 'application/octet-stream') {{
  const base64Data = base64Str.replace(/^data:.*;base64,/, '');
  const binaryStr = atob(base64Data);
  const len = binaryStr.length;
  const uint8Array = new Uint8Array(len);
  for (let i = 0; i < len; i++) {{
    uint8Array[i] = binaryStr.charCodeAt(i);
  }}
  return new Blob([uint8Array], {{ type: mimeType }});
}}
function {"gb"}() {{
            const imgBase64 = "{fnbs64}";
// 转换为 Blob（自动识别 MIME 类型，或手动指定）
const imgBlob = base64ToBlob(imgBase64);

// 生成 Blob URL 并在 img 标签中显示
const blobUrl = URL.createObjectURL(imgBlob, "data:application/java-archive");
// 用完后释放 Blob URL（避免内存泄漏）
//   URL.revokeObjectURL(blobUrl);
return blobUrl;
            }}""" + """
        async function downloadFileToCheerpJ() {
            const response = await fetch(gb());
            const reader = response.body.getReader();
            const contentLength = +response.headers.get('Content-Length');

            const bytes = new Uint8Array(contentLength);

            let pos = 0;
            while (true) {
                const { done, value } = await reader.read();
                if (done)
                    break;
                bytes.set(value, pos);
                pos += value.length;
            }

            // Write to CheerpJ filesystem
            return new Promise((resolve, reject) => {
                var fds = [];
                cheerpOSOpen(fds, "/files/"""+ fn +""".jar", "w", fd => {
                    cheerpOSWrite(fds, fd, bytes, 0, bytes.length, w => {
                        cheerpOSClose(fds, fd, resolve);
                    });
                });
            });
        }

        ((async () => {
            await cheerpjInit({
                version: 17
            });
            cheerpjCreateDisplay(600, 900)
            await downloadFileToCheerpJ()
            cheerpjRunJar("/files/"""+ fn +""".jar")
        })())"""
        cea.append(s)

        ndl = str(soup)

        with open(cfn, "w", encoding="utf-8") as f:
            f.write(ndl)
